/*
 * HTMLDocument.cpp
 *
 *  Created on: 2010-6-10
 *      Author: guobc
 */

#include "HTMLDocument.h"

namespace HA {

HTMLDocument::HTMLDocument() :
	HA::ASTDom(), mRoot(NULL) {

}

bool HTMLDocument::open(const string& htmlName) {
	string buffer("");
	URL url(htmlName);
	if (!url.getProtocol().empty()) {
		URLConnection connection(url);
		if (connection.connect() < 0) {
			return false;
		}
		connection.download(buffer);
	} else {
		ifstream fin;
		fin.open(htmlName.c_str());
		char ch;
		while (fin.good()) {
			fin.get(ch);
			buffer.push_back(ch);
		}
	}
	if (buffer.empty())
		return false;
	mLexer = new HTMLLexer(buffer);
	return true;
}

void HTMLDocument::close() {
	if(mLexer != NULL){
		mLexer->clear();
		delete mLexer;
	}
}

void HTMLDocument::parse() throw (exception) {
	try {
		if (mLexer != NULL) {
			Parser* parser(new HTMLParser(mLexer));
			parser->parse();
			mRoot = dynamic_cast<Element*> (parser->getRootNode());
			delete parser;
		}
	} catch (exception& e) {
		throw e;
	}
}
}
